package cn.asura.controller;

import cn.asura.pojo.Blog;
import cn.asura.service.BlogService;
import cn.asura.service.BlogViewsService;
import cn.asura.utils.IpAddressUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author Asura
 * @description
 * @createTime 2020-09-18 19:30
 */
@Controller
@RequestMapping("/view")
public class ViewController {

    private BlogService blogService;
    private BlogViewsService blogViewsService;

    @Autowired
    public void setBlogService(BlogService blogService) {
        this.blogService = blogService;
    }

    @Autowired
    public void setBlogViewsService(BlogViewsService blogViewsService) {
        this.blogViewsService = blogViewsService;
    }

    @RequestMapping("/admin")
    public String admin() {
        return "view/index";
    }

    @RequestMapping("/index")
    public String index() {
        return "view/index";
    }

    @GetMapping("/queryData")
    public ModelAndView getBlogsByRule(String type) {
        System.out.println("type = " + type);
        List<Blog> blogs = blogService.getBlogsByRule(type);
        ModelAndView modelAndView = new ModelAndView("view/datas");
        modelAndView.addObject("datas", blogs);
        return modelAndView;
    }

    @GetMapping("/info")
    public String blogInfo(int blogId, HttpServletRequest request) {
        //根据blogId去查blog
        Blog blog = blogService.findByBlogId(blogId);
        //给info的view+1
        blogService.addView(blogId);
        System.out.println(blog);
        request.setAttribute("blogInfo", blog);
        // 获取ip
        String ip = IpAddressUtil.getIpAddress(request);
        System.out.println(ip);
        // 获取博客的userid
        int userId = blog.getUserId();
        boolean b = blogViewsService.add(blogId, ip, userId);
        System.out.println(b);

        return "view/info";
    }

}
